<template>
	<div style="padding-bottom: 40px;">
		<div class="fixed-header">
			<van-sticky>
				<div class="topdropdown">
					<van-dropdown-menu>
						<van-dropdown-item v-model="params.storesId" :options="option1" title="店铺" @change="storeChange"/>
						<van-dropdown-item v-model="searchObj.value2" :options="option2" title="状态" @change="statusChange"/>
					</van-dropdown-menu>
					<div class="dropdownLeft" v-if="params.storesId"></div>
					<div class="dropdownRight" v-if="searchObj.value2"></div>
				</div>
				<div class="searchBox">
					<van-search v-model="params.deviceName" :placeholder="placeholder" @search="handleSearch">
						<template #right-icon>
							<div class="search-confirm" @click.stop="handleSearch">
								<span style="margin-right: 10px;height: 24px;">|</span>
								<span class="search-text">搜索</span>
							</div>
						</template>
					</van-search>
				</div>
			</van-sticky>
		</div>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" finished-text="没有更多数据了"
				:finished="finished" @load="getdata">
				<!-- <DeviceList :list="list" :mark="mark" @deviceUnbind="Unbind"></DeviceList> -->
				<div style="padding: 0 10px">
					<div class="grid-content" v-for="(item, index) in list" :key="index">
						<div>
							<div class="grid-content-top-pic">
								<div class="flex">
									<div>
										<img class="imgage" src="../../../assets/images/shebei.png" alt="">
									</div>
									<div style="margin-left: 10px; font-size: 12px;">
										{{ item.deviceName }}
									</div>
								</div>
								<div class="grid-content-top-pic-right">
									<van-tag v-if="item.deviceStatus === 0" type="success" size="large">在线</van-tag>
									<van-tag v-else type="danger" size="large">离线</van-tag>
								</div>
							</div>
							<div class="grid-content-top-dec">
								<p class="grid-content-top-dec-p">
									<span class="grid-content-top-dec-span">编号：{{ item.deviceNumber }}</span>
									<span class="grid-content-top-dec-span">店铺名称：{{ item.storeName }}</span>
								</p>
								<p class="grid-content-top-dec-p">
									<span class="grid-content-top-dec-span">绑定时间：{{ item.bindTime }}</span>
									<span class="grid-content-top-dec-span">激活时间：{{ item.createTime }}</span>
								</p>
							</div>
						</div>
						<div class="divider"></div>
						<div class="grid-content-bottom">
							<p @click="ViewQRcode(item.qmCode)">查看二维码</p>
							<span style="color: #c1c5cd">|</span>
							<p @click="deviceTransfershe(item)">设备转移</p>
							<span style="color: #c1c5cd">|</span>
							<p @click="senDpulses(item)">远程上分</p>
							<span style="color: #c1c5cd">|</span>
							<p @click="Unbind(item)">解除绑定</p>
						</div>
					</div>
				</div>
			</van-list>
		</van-pull-refresh>
		<!-- 弹窗 -->
		<van-dialog v-model:show="dialogshow" title="提示" show-cancel-button @confirm="dialogConfirm"
			@cancel="dialogCancel" :keyboard-enabled="false">
			<div class="prompt">确定要解绑该设备吗?</div>
		</van-dialog>
		<!-- 转移设备 -->
		<van-popup v-model:show="storePicker" destroy-on-close position="bottom" safe-area-inset-bottom round>
			<van-picker title="请选择您想转入的店铺" :loading="storeloading" :columns="storecolumns" @cancel="storePicker = false"
				:model-value="storepickerValue" @confirm="storeConfirm" />
		</van-popup>
		<!-- 远程上分 -->
		<van-dialog v-model:show="scoreShow" title="远程上分" :showConfirmButton="false" :keyboard-enabled="false">
			<van-form @submit="scoreSubmit" input-align="right" error-message-align="right" ref="formRef"
				:submit-on-enter="false">
				<van-cell-group inset>
					<van-field name="count" label="上分数量" :rules="[{ required: true, message: '请输入上分数量' }]" 
						@blur="countblur" v-model="scoreParams.count" type="number" :min="1" placeholder="请输入上分数量">
					</van-field>
					<van-field name="proportion" label="比例" type="digit" :rules="[{ required: true, message: '请输入比例' }]" 
						@change="proportionblur">
						<template #input>
							<van-stepper v-model="scoreParams.proportion" max="10" integer input-width="36px"/>
						</template>
					</van-field>
				</van-cell-group>
				<div style="margin: 16px 0;" class="flexaround">
					<van-button round block type="default" @click="handleReset" style="width: 40%">取消</van-button>
					<van-button round block type="primary" native-type="submit" style="width: 40%">提交</van-button>
				</div>
			</van-form>
		</van-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from "vue";
	import {
		getUserid
	} from '@/utils/auth';
	import {
		deviceEntityList,
		deviceEntityUnbind,
		deviceTransfer,
		senDpulse
	} from "@/api/deviceEntity";
	import {
		StoresList
	} from "@/api/deviceRechargeConfig";
	import {
		showToast,
		showDialog
	} from 'vant';
	import {
		useRouter
	} from 'vue-router';
	const router = useRouter();

	onMounted(() => {
		getdata();
		getstore();	//店铺
	});
	//设备转移
	const storeloading = ref(false);
	const storePicker = ref(false);
	const storecolumns = ref([]);
	const storepickerValue = ref([]);
	const transferParams = ref({
		deviceId: '',
		nowStoreId: '',
		userId: getUserid(),
	});


	const loading = ref(false);
	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);

	const placeholder = ref('按设备号或店铺名称搜索');
	const mark = ref('device');
	const dialogshow = ref(false); //解绑组件
	const unbindId = ref(undefined); //解绑设备的id
	const params = ref({
		size: 10,
		pages: 1,
		userId: getUserid(),
		deviceName:'',
		storesId:'',
		deviceStatus: '',
	});
	const list = reactive([]);
	var option1 = reactive([]);


	const option2 = [{
		text: '全部',
		value: ''
	}, {
		text: '在线',
		value: 1
	}, {
		text: '离线',
		value: 2
	}];

	const searchObj = ref({
		value2: '',
	});
	//店铺
	const getstore = async () => {
		const userId = {
			userId: getUserid(),
		}
		try {
			const response = await StoresList(userId);
			const records = response.data || [];
			option1 = [{
				text: "全部",
				value: ''
			}, ...records.map((item) => ({ // 展开原数组
				text: item.storeName,
				value: item.id,
			}))];
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	}

	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceEntityList(params.value);
			const records = response.data.records || [];
			 // 新增：格式化时间
			 const formattedRecords = records.map(item => ({
				...item,
				// 添加格式化后的时间字段（保留原始 createTime）
				createTime: formatISODate(item.createTime),
				bindTime: formatISODate(item.bindTime)
			}));

			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...formattedRecords);
			} else {
				list.push(...formattedRecords);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error('获取数据失败', err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	// 店铺切换
	const storeChange = () =>{
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 状态切换
	const statusChange = (status) =>{
		if(status){
			params.value.deviceStatus = Number(status) - 1;
		}else{
			params.value.deviceStatus = '';
		}
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
		params.value.deviceName = '';
		params.value.storesId = '';
		params.value.deviceStatus = '';
		searchObj.value.value2 = '';

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 输入框搜索
	const handleSearch = () => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};
	//二维码
	const ViewQRcode = (qmCode) => {
		router.push({
			name: 'codeImage',
			params: {
				qmCode: qmCode
			}
		})
	};
	// 设备转移
	const deviceTransfershe = async (item) => {
		transferParams.value.deviceId = item.id;
		storeloading.value = true;
		var userId = {
			userId: getUserid()
		}
		try {
			const response = await StoresList(userId);
			const records = response.data || [];
			storecolumns.value = [
				records.map((item) => ({ // 展开原数组
					text: item.storeName,
					value: item.id,
				}))
			];
			storePicker.value = true;
			storeloading.value = false;
		} catch (err) {
			//console.log(err)
		}
	};
	const storeConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		storepickerValue.value = selectedValues;
		transferParams.value.nowStoreId = selectedValues[0];
		showDialog({
			title: '提示',
			message: '您确定要转入该店铺吗？',
			showCancelButton: true
		}).then(async () => {
			try {
				const response = await deviceTransfer(transferParams.value);
				if (response.status == 200) {
					showToast({
						type: 'success',
						message: '转入成功',
						forbidClick: true,
						duration: 1000
					});
					setTimeout(() => {
						onRefresh();
						storePicker.value = false;
					}, 1000)
				} else {
					showToast({
						type: 'fail',
						message: response.desc || '转入失败',
						forbidClick: true,
						duration: 1000
					});
				}
			} catch (error) {
				showToast({
					type: 'fail',
					message: error.desc || '转入失败',
					forbidClick: true,
					duration: 1000
				});
			}
		}).catch(() => {
			// on cancel
		});;
	};
	//上分
	const scoreShow = ref(false);
	const scoreParams = ref({
		deviceNumber: undefined,
		count: 1, //上分数量
		proportion: 1, //比例
		userId: getUserid(),
	})
	const senDpulses = (item) => {
		if(item.deviceStatus === 0){
			scoreParams.value.deviceNumber = item.deviceNumber;
			scoreShow.value = true;
		} else {
			showToast({
				type: 'fail',
				message: '当前设备不在线，无法上分',
				forbidClick: true,
				duration: 1000
			});
		}
	};
	const countblur = () => {
		if(scoreParams.value.count > 100){
			scoreParams.value.count = 1
			showToast({
				type: 'fail',
				message: '请输入1-100的数字',
				forbidClick: true,
				duration: 1000
			});
		}
	};
	const proportionblur = () => {
		if(scoreParams.value.proportion > 10){
			// scoreParams.value.proportion = 1
			showToast({
				type: 'fail',
				message: '请输入1-10的数字',
				forbidClick: true,
				duration: 1000
			});	
		}
	}
	const scoreSubmit = async () => {
		if(scoreParams.value.count > 100){
			return;
		}
		if(scoreParams.value.proportion > 10){
			return;
		}
		try {
			// 先进行表单验证
			await formRef.value.validate();
			const response = await senDpulse(scoreParams.value);

			if (response.status == 200) {
				showToast({
					type: 'success',
					message: '上分成功',
					forbidClick: true,
					duration: 1000
				});
				setTimeout(() => {
					handleReset();
					onRefresh();
				}, 1000)
			} else {
				showToast({
					type: 'fail',
					message: response.desc || '上分失败',
					forbidClick: true,
					duration: 1000
				});
			}
		} catch (error) {
			showToast({
				type: 'fail',
				message: error.desc || '上分失败',
				forbidClick: true,
				duration: 1000
			});
		}
	};
	// 表单引用
	const formRef = ref(null);
	// 重置表单
	const handleReset = () => {
		formRef.value.resetValidation(); // 清除验证提示
		scoreParams.value = {
			deviceNumber: undefined,
			count: 1,
			proportion: 1,
			userId: getUserid(),
		};
		scoreShow.value = false;
	};

	function Unbind(item) {
		dialogshow.value = true;
		unbindId.value = item.id;
	};
	//确认解绑
	const dialogConfirm = async () => {
		var params = {
			id: unbindId.value
		}
		try {
			const response = await deviceEntityUnbind(params);
			if (response.status == 200) {
				showToast({
					type: 'success',
					message: '解绑成功',
					forbidClick: true,
					duration: 1000
				});
			} else {
				showToast({
					type: 'fail',
					message: response.desc,
					forbidClick: true,
					duration: 1000
				});
			}
			setTimeout(() => {
				handleSearch();
			}, 1000)
		} catch (err) {
			showToast({
				type: 'fail',
				message: err.desc,
				forbidClick: true,
				duration: 1000
			});
		}
	};
	//取消解绑
	const dialogCancel = () => {
		unbindId.value = undefined;
	};
	  // 时间格式化工具函数
	  const formatISODate = (isoString) => {
		// 修复格式问题：将 "+0000" 转成 "+00:00"
		if (!isoString) return "-"; // 处理空值
		try {
			const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
			const date = new Date(fixedDateString);
			// 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
			return date.toLocaleString("zh-CN", {
				year: "numeric",
				month: "2-digit",
				day: "2-digit",
				hour: "2-digit",
				minute: "2-digit",
				// second: "2-digit",
				hour12: false // 强制 24 小时制
			}).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
		} catch {
			return "-"; // 解析失败时返回占位符
		}
	};
</script>

<style scoped lang="scss">
	:deep(.van-dropdown-menu__bar) {
		box-shadow: none;

		.van-dropdown-menu__title {
			color: orange;
		}

		.van-dropdown-menu__title:after {
			border-color: transparent transparent orange orange;
		}
	}

	:deep(.searchBox) {
		.van-search {
			background-color: white;

			// 搜索框
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				// border-radius: 5px;
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2FBC3C;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		// 文字
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}

	.topdropdown {
		position: relative;

		.dropdownLeft {
			position: absolute;
			bottom: 0;
			left: 16%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}

		.dropdownRight {
			position: absolute;
			bottom: 0;
			right: 14%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}
	}

	.flexbetween {
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-around;
	}

	.flexaround {
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-around;
	}

	.flex {
		display: flex;
		align-items: center;
		align-content: center;
	}

	.grid-content {
		// border: 1px solid #c1c5cd;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-top: 20px;
		background-color: white;

		.grid-content-top-dec {
			padding: 0 10px;

			.grid-content-top-dec-p {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 12px;
				margin-top: 0;

				.grid-content-top-dec-span {
					width: 50%;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}

		.grid-content-top-pic {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			padding: 10px;
			box-sizing: border-box;

			.imgage {
				width: 58px;
				height: 58px;
				border-radius: 10px;
			}

			.grid-content-top-pic-right {
				margin-left: 10px;
				font-size: 12px;
			}
		}

		.grid-content-bottom {
			display: flex;
			align-items: center;
			align-content: center;
			justify-content: space-around;
			padding: 0 10px;
			width: 100%;
			font-size: 12px;
			color: rgb(81, 164, 208);
			box-sizing: border-box;

			p {
				cursor: pointer;
			}
		}
	}


	.divider {
		width: 100%;
		height: 1px;
		border-bottom: 1px solid #c1c5cd;
	}

	.prompt {
		margin: 8px 0;
		text-align: center;
	}
</style>